//
//  RadioPlayViewController.m
//  LWB_Project
//
//  Created by lanou3g on 15/11/17.
//  Copyright © 2015年 wangjianliang. All rights reserved.
//

#import "RadioPlayViewController.h"
#import "RadioPlayTableViewCell.h"
#import "RadioViewController.h"
#import "WNetDealTools.h"
 #import "MusicPlayerHelper.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#define KMusicPlayerHelper [MusicPlayerHelper sharedMusicPlayerHelper]
@interface RadioPlayViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    BOOL isReshing;
    BOOL isLoading;
}
@property (weak, nonatomic) IBOutlet UITableView *radioPlayTableView;
@property (weak, nonatomic) IBOutlet UIImageView *radioImageView;
- (IBAction)playOrPauseButton:(id)sender;
@property (weak, nonatomic) IBOutlet UISlider *playSlider;
@property (strong, nonatomic) IBOutlet UILabel *currenTimeLable;
@property (strong, nonatomic) IBOutlet UILabel *AllTimeLable;
@property (strong, nonatomic) IBOutlet UIImageView *backImage;
@property (strong, nonatomic) IBOutlet UIButton *startButton;


@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation RadioPlayViewController

static RadioPlayViewController *share = nil;
static RadioModel *currentModel;
static FMPlayingModel *currentPlayModel;
static NSInteger currentPlayNum = -1;

#pragma mark---  旋转角度控制
static int Rotationi = 0;
#pragma mark--- 旋转时间
static float RotationTime = 0.1;

+(instancetype)shareRadioPlayViewController
{
        if (share == nil) {
            share = [[RadioPlayViewController alloc]init];
        }

        return share;
}

-(void)viewWillAppear:(BOOL)animated
{
 //传递 model 信息 进行网络下载 页面刷新
    //第二次之后 都走这个方法 不走 viewDidLoad
    //网络下载
    
    
    #pragma mark--- 如果模型改变则下载资源
    if([currentModel.tid isEqualToString:_model.tid] == NO)
    {
        currentModel  = _model;
        currentPlayNum = 0;
        self.dataArray = [NSMutableArray array];
        __block RadioPlayViewController *playVC = self;
        [WNetDealTools dealRadioPlayListModelTid:_model.tid pages:currentPlayNum Block:^(NSArray *ModelArray)
         {
            [playVC.dataArray addObjectsFromArray:ModelArray];
            [playVC.radioPlayTableView reloadData];
             
             //第一次直接点击进去 不能程序崩溃！！！！
            if (ModelArray.count != 0)
            {
                RadioPlayModel *model = playVC.dataArray[0];
                currentPlayNum = 0;
                
                 //加载转圈的图片！
                 [playVC.radioImageView sd_setImageWithURL:[NSURL URLWithString:_model.imgsrc]];
                 if ([_model.imgsrc isEqualToString:@""]) {
                    playVC.radioImageView.image = [UIImage imageNamed:@"u=1470722442,2591575796&fm=11&gp=0.jpg"];
                     
                     //u=3033764978,2384825325&fm=21&gp=0
                 }
                
                //运行第一个资源 音乐播放
                [WNetDealTools getFMPlayingDataWithUrl:model.docid Playblock:^(FMPlayingModel *model)
                 {
                     if (![currentPlayModel.url_mp4 isEqualToString: model.url_mp4])
                     {
                         currentPlayModel = model;
                         [KMusicPlayerHelper playBackgroundMusicURLString:model.url_mp4];

                     }
                 }];
            
            }
             
             if (ModelArray.count == 20) {
                 currentPlayNum++;
             }

            
            
         }];
    }


    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];

    self.radioPlayTableView.dataSource = self;
    self.radioPlayTableView.delegate = self;
    [self.radioPlayTableView registerNib:[UINib nibWithNibName:@"RadioPlayTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    
    #pragma mark--- 稍微延时就 变成圆形
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.radioImageView.layer.masksToBounds = YES;
        self.radioImageView.layer.cornerRadius = (CGFloat)self.radioImageView.frame.size.height/2.0;

        self.currenTimeLable .layer.masksToBounds = YES;
        self.currenTimeLable .layer.cornerRadius = (CGFloat)self.currenTimeLable .frame.size.height/2.0;
  
        self.AllTimeLable.layer.masksToBounds = YES;
        self.AllTimeLable.layer.cornerRadius = (CGFloat)self.AllTimeLable.frame.size.height/2.0;
    });
    

    
    //进度不停地返回
    __weak typeof(self) WeakSelf = self;
    KMusicPlayerHelper.blocktime = ^(CGFloat time , CGFloat value)
    {
        //更新总时间
        CGFloat alltime = [KMusicPlayerHelper getTimelength];
        WeakSelf.AllTimeLable.text =
        [NSString stringWithFormat:@"%02d分:%02d秒",(int)alltime/60,(int)alltime%60];
        //更新时间显示
        WeakSelf.currenTimeLable.text = [NSString stringWithFormat:@"%02d分:%02d秒",(int)time/60,(int)time%60];
        //更新进度
        WeakSelf.playSlider.value = value;
        
        
        //图片旋转
        [WeakSelf addtime];
    };
    
    
        __block RadioPlayViewController *newVC = self;
    //上拉加载:
    [self.radioPlayTableView addFooterWithCallback:^{
        if (newVC->isReshing) {
            return;
        }

        newVC->isLoading = YES;
        [WNetDealTools dealRadioPlayListModelTid:_model.tid pages:currentPlayNum Block:^(NSArray *ModelArray)
         {
             [newVC.dataArray addObjectsFromArray:ModelArray];
             [newVC.radioPlayTableView reloadData];
             
             //第一次直接点击进去 不能程序崩溃！！！！
             if (ModelArray.count != 0)
             {
                 RadioPlayModel *model = newVC.dataArray[0];

                 //运行第一个资源 音乐播放
                 [WNetDealTools getFMPlayingDataWithUrl:model.docid Playblock:^(FMPlayingModel *model)
                  {
                      if (![currentPlayModel.url_mp4 isEqualToString: model.url_mp4])
                      {
                          currentPlayModel = model;
                          [KMusicPlayerHelper playBackgroundMusicURLString:model.url_mp4];
                      }
                  }];
                 
             }
             if (ModelArray.count == 20) {
                 currentPlayNum++;
             }
             
             
             [newVC.radioPlayTableView footerEndRefreshing];
         }];

        newVC->isLoading = NO;

        
    }];

    //添加观察者
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RadioStop:) name:@"RadioStop" object:nil];
}

-(void)RadioStop:(NSNotification *)sender
{
    [KMusicPlayerHelper playStop];
    [self.startButton  setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
}


#pragma mark--- 控制图片旋转
-(void)addtime
{
    Rotationi++;
    //这个是 旋转一个角度
    [UIView animateWithDuration:RotationTime animations:^
     {
         self.radioImageView.transform = CGAffineTransformMakeRotation((Rotationi%180) * (M_PI /90 ));
     }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RadioPlayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"u=391&gp=0-1.jpg"]];
   
    RadioPlayModel *model = self.dataArray[indexPath.row];
    [cell setModel:model];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    RadioPlayModel *model = self.dataArray[indexPath.row % self.dataArray.count];
    currentPlayNum = indexPath.row;
    [WNetDealTools getFMPlayingDataWithUrl:model.docid Playblock:^(FMPlayingModel *model)
     {
        if (![currentPlayModel.url_mp4 isEqualToString: model.url_mp4])
        {
            currentPlayModel = model;
            [KMusicPlayerHelper playBackgroundMusicURLString:model.url_mp4];
            [self.startButton  setImage:[UIImage imageNamed:@"iconfont-bofangqibofang"] forState:UIControlStateNormal];
            

        }
    }];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)playOrPauseButton:(UIButton *)sender
{
    if (KMusicPlayerHelper.isPlayer) {
        
        [KMusicPlayerHelper playStop];
        [sender  setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    }
    else
    {
        [KMusicPlayerHelper playstart];
        [sender  setImage:[UIImage imageNamed:@"iconfont-bofangqibofang"] forState:UIControlStateNormal];
        

        
    }
    
}

- (IBAction)SliderValuechange:(UISlider *)sender {
    
    [KMusicPlayerHelper changeprogess:sender.value];
    
}

- (IBAction)previous:(UIButton *)sender {
    
    
    if (currentPlayNum>0)
    {
        RadioPlayModel *model = self.dataArray[(currentPlayNum--) %self.dataArray.count];
        [WNetDealTools getFMPlayingDataWithUrl:model.docid Playblock:^(FMPlayingModel *model)
         {
             if (![currentPlayModel.url_mp4 isEqualToString: model.url_mp4])
             {
                 currentPlayModel = model;
                 [KMusicPlayerHelper playBackgroundMusicURLString:model.url_mp4];
             }
         }];
        
        
        //self.radioPlayTableView.contentOffset = CGPointMake(0, 80 *currentPlayNum);
    }
        


}

- (IBAction)next:(UIButton *)sender
{
    if ( currentPlayNum < (self.dataArray.count - 1) )
    {
        RadioPlayModel *model = self.dataArray[(currentPlayNum++) %self.dataArray.count];
        [WNetDealTools getFMPlayingDataWithUrl:model.docid Playblock:^(FMPlayingModel *model)
         {
             if (![currentPlayModel.url_mp4 isEqualToString: model.url_mp4])
             {
                 currentPlayModel = model;
                 [KMusicPlayerHelper playBackgroundMusicURLString:model.url_mp4];
             }
         }];
        //self.radioPlayTableView.contentOffset = CGPointMake(0, 80 *currentPlayNum);
    }
    
 }


@end
